package cn.yl.fxboot.application.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;

import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.yl.fxboot.application.action.MsgPaneActions;
import cn.yl.fxboot.application.common.config.GlobalConfig;
import cn.yl.fxboot.application.service.ffmpeg.FFmpegCallback;
import cn.yl.fxboot.application.service.ffmpeg.FFmpegCommand;
import cn.yl.fxboot.application.service.ffmpeg.FFmpegCommandBuilder;
import javafx.application.Platform;

@Component
public class MixVideoUtil {
	
	public static String getFFMPEG_PATH() {
		try {
			//return ResourceUtils.getFile("classpath:script/ffmpeg.exe").getAbsolutePath();
			return GlobalConfig.FFMPEGPath;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Platform.runLater(()->{
				MsgPaneActions.doLog("error:cant find ffmpeg"+e.getLocalizedMessage());
			});
		}
		return null;
	}
	
	/**
	 * 有序合成视频，
	 * @param output 输出文件夹
	 * @param dir 输入文件夹
	 * @param pathList 输入文件路径
	 */
	public static void javaMix(String output,String dir,ArrayList<String> pathList) {
		try {
			/**
			 * 先将视频转成TS:ffmpeg -i 1.mp4 -vcodec copy -acodec copy -vbsf h264_mp4toannexb 1.ts
			 * 再拼接ffmpeg -f concat -safe 0 -i filelist.txt -c copy output.mp4
			 */
			//1.转成ts
			ArrayList<String> outputList = new ArrayList<>();
			String tmpPath = output + "\\\\tmp";
			FileUtil.mkdir(tmpPath);
			for(String path : pathList) {
				String tmpOutput =  tmpPath+ "\\\\" + IdUtil.fastSimpleUUID() + ".ts";
				FFmpegCommandBuilder builder = new FFmpegCommandBuilder(getFFMPEG_PATH());
				FFmpegCommand cmd = builder.input(path).vcodecCopy().acodecCopy().h264ToTs().output(tmpOutput).build();
				cmd.start(new FFmpegCallback<Void>() {

					@Override
					public Void complete(String line) {
						MsgPaneActions.doLog(line);
						return null;
					}

					@Override
					public Void processStream(String line) {
						// TODO Auto-generated method stub
						//MsgPaneActions.doLog(line);
						return null;
					}

					@Override
					public Void error(String err) {
						// TODO Auto-generated method stub
						MsgPaneActions.doLog("error:"+err);
						return null;
					}
				});
				outputList.add("file "+"'"+tmpOutput+"'");
			}
			
			//2.创建filelist.txt
			String fileList = output + "\\" + "filelist.txt";
			File txt = FileUtil.file(fileList);
			FileUtil.writeLines(outputList, txt, Charset.forName("UTF-8"));
			//3.拼接
			String outputFilePath = output + "\\" +System.currentTimeMillis()+ "mix.mp4";
			FFmpegCommandBuilder builder = new FFmpegCommandBuilder(getFFMPEG_PATH());
			builder.force().concat().safe0().input(fileList).cCopy().output(outputFilePath);
			builder.build().start(new FFmpegCallback<Void>() {

				@Override
				public Void complete(String line) {
					MsgPaneActions.doLog(line);
					return null;
				}

				@Override
				public Void processStream(String line) {
					// TODO Auto-generated method stub
					//MsgPaneActions.doLog(line);
					return null;
				}

				@Override
				public Void error(String err) {
					// TODO Auto-generated method stub
					MsgPaneActions.doLog("error:"+err);
					return null;
				}
			});
			//4.删除多余文件
			FileUtil.clean(tmpPath);
		}catch(Exception e) {
			MsgPaneActions.doLog("error:"+e.getLocalizedMessage());
		}
	}
	
	 public static void mix(String output ,String[] pathList) {
	    	try {
				String script = ResourceUtils.getFile("classpath:script/mix.py").getAbsolutePath();
				String[] args1 = new String[] { "python", script,output};
				String[] totalArgs = ArrayUtil.addAll(args1,pathList);
				Process pr = Runtime.getRuntime().exec(totalArgs);
				printMessage(pr.getInputStream());
				printMessage(pr.getErrorStream());
				pr.waitFor();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	    }
	 
	 public static void mixByName(String output,String dir ,String[] pathList) {
	    	try {
				String script = ResourceUtils.getFile("classpath:script/mix.py").getAbsolutePath();
				String[] args1 = new String[] { "python", script,output};
				String[] totalArgs = ArrayUtil.addAll(args1,pathList);
				Process pr = Runtime.getRuntime().exec(totalArgs);
				printMessage(pr.getInputStream());
				printMessage(pr.getErrorStream());
				pr.waitFor();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	    }
	    
	    private static void printMessage(final InputStream input) {
	    	new Thread(new Runnable() {
	    		public void run() {
	    			BufferedReader bf = new BufferedReader(new InputStreamReader(input));
	    			String line = null;
	    			try {
	    				while((line=bf.readLine()) != null) {
	    					System.out.println(line);
	    					MsgPaneActions.doLog(line);
	    				}
	    			}catch (Exception e) {
	    				e.printStackTrace();
	    			}
	    		}
	    	}).start();
	      }
	    
	    
	   
}
